﻿using System;
using System.Data;
using System.Text;
using System.Data.SQLite;
using Common.DataBase.Interface;
using Common.DataBase.Implement;
using Common.Utils;
using System.Data.Common;
using ScanFile.Model;
using System.Collections.Generic;

namespace ScanFile.Dal{

	public partial class FileExDal : BaseDal<FileEx> {
    
		/// <summary>
		/// 构造函数
		/// </summary>
		public FileExDal(){

		}

    public System.Int64 DeleteFileExByPathMd5(string pathMd5) {
      string sql = string.Format("	DELETE FROM {0} WHERE pathMd5 = '{1}';", tableName, pathMd5);
      return _sqlHelper.ExecuteNonQuery(sql, true);
    }

    public System.Int64 UpdateSameFileCount(FileEx fileEx) {
      if (string.IsNullOrWhiteSpace(fileEx.Md5)) {
        return 0;
      } else {
        string sql = string.Format("	UPDATE {0} SET sameFileCount = (SELECT sameFileCount FROM (SELECT COUNT(1) as sameFileCount FROM {0} WHERE MD5 = '{1}')Temp) WHERE MD5 = '{1}';", tableName, fileEx.Md5);
        return _sqlHelper.ExecuteNonQuery(sql,true);
      }
    }

    public List<FileEx> GetListByParentFolder(string folderPathMd5) {
      string sql = string.Format("SELECT * FROM {0} WHERE folderMd5=@folderMd5", tableName);
      return _sqlHelper.FindList<FileEx>(sql,CommandType.Text,new DbParameter[] { DbParam("@folderMd5", folderPathMd5) });
    }


    public List<FileEx> GetListByMd5(string fileMd5) {
      string sql = string.Format("SELECT * FROM {0} WHERE md5=@md5", tableName);
      return _sqlHelper.FindList<FileEx>(sql, CommandType.Text, new DbParameter[] { DbParam("@md5", fileMd5) });
    }



    public FileEx GetFileExByFullPath(string fileFullName) {
      string sql = string.Format("SELECT * FROM {0} WHERE fullName=@fileFullName", tableName);
      return FindBySQL(sql, new DbParameter[] { DbParam("@fileFullName", fileFullName) });
    }

    public FileEx GetFileExByPathMd5(string pathMd5) {
      string sql = string.Format("SELECT * FROM {0} WHERE pathMd5=@pathMd5", tableName);
      return FindBySQL(sql, new DbParameter[] { DbParam("@pathMd5", pathMd5) });

    }

    public System.Int64 DeleteOrphanFolderEx(string folderFullName) {
      string sql = string.Format("DELETE FROM {0}  WHERE INSTR(folderFullName,@folderFullName)   = 1 ", tableName);
      return _sqlHelper.ExecuteNonQuery(sql, CommandType.Text, new DbParameter[] { DbParam("@folderFullName", folderFullName) });
    }

    public List<FileEx> GetSameFiles() {
      string sql = string.Format("SELECT * FROM {0} WHERE sameFileCount > 1 AND pathMd5 IN (SELECT max(pathMd5) FROM fileex WHERE sameFileCount > 1 GROUP BY md5) limit 0,200 ", tableName);
      return _sqlHelper.FindList<FileEx>(sql, CommandType.Text, new DbParameter[] { });
    }

  }
}
